<template>
    <el-row :gutter="20" style="margin-left:5px;" class="maxh100">
        <el-col :span="8">

            <el-dropdown class="dropdown-font" @command="handleCommand">
                <span class="el-dropdown-link">
                    {{ bank.name }}
                    <el-icon class="el-icon--right">
                        <arrow-down />
                    </el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item :command="item.id" v-for="(item, index) in bankList" :key="index">
                            {{ item.name }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
            <div class="collect-shuffle-font">
                <el-button type="primary" :icon="Switch" link @click="sortFlag = !sortFlag">{{ sortFlag ? "顺序答题" :
                    "乱序答题"
                    }}</el-button>
            </div>
            <el-scrollbar height="800px">
                <el-collapse class="collapse-item-font" v-model="activeNames">
                    <el-collapse-item v-for="item in teamNumData" :key="item.id" :title="item.label" :name="item.id">

                        <template v-if="item.children != null">
                            <el-card @click="handlerQuestionDetail(team.id, team.questionIndex, team.questionId)"
                                shadow="hover" v-for="team in item.children" :key="team.id" class="team-card"
                                body-style="padding-top: 0px;padding-bottom: 0px;">
                                <template #header>
                                    <div class="card-header">
                                        <span>{{ team.label }}</span>
                                    </div>
                                </template>

                                <div class="team-progress">
                                    <el-progress :percentage="teamPerNum(team)" />
                                </div>
                                <span>已练习 {{ team.questionIndex }}/{{ team.questionNum }}</span>

                            </el-card>
                        </template>
                    </el-collapse-item>
                </el-collapse>
            </el-scrollbar>
        </el-col>
        <el-col :span="16">

            <el-progress :percentage="progressNum" :show-text="false" />
            <el-card class="right-card">
                <!--循环问题列表到走马灯效果中-->
                <el-carousel ref="carousel" :initial-index="1" @change="handleChange" style="width: 100%;height: 550px;"
                    :autoplay="false" :loop="false" indicator-position="none" arrow="never">

                    <el-carousel-item>
                        <h3 text="2xl" justify="center">请选择题组信息</h3>
                    </el-carousel-item>
                    <template v-if="questionAndAnswerData !== null && questionAndAnswerData.length != 0">
                        <el-carousel-item v-for="(item, index) in questionAndAnswerData" :name="item.id" :key="index">

                            <el-card style="width: 100%;height: 99%;">
                                <span class="question-content">{{ index + 1 }}.{{ item.content }}</span>

                                <!--判断是单选还是多选-->
                                <template v-if="item.type == 1">
                                    <!--动态设置model为该面板的问题id-->
                                    <el-radio-group v-model="tempQuestionObj[item.id]"
                                        @change="(val) => { radioAnswer(item.id, item.rightAnswerId, val) }"
                                        class="radio-column" size="large">
                                        <!-- @click="radioAnswer(item.id, answer.id, ind)" 
                                    :class="{ radio_error: isActive &&  tempQuestionObj[item.id] == answer.id}"
                                    -->
                                        <div v-for="(answer, ind) in item.answerList" :key="ind" class="answer-item">
                                            <el-radio-button
                                                :class="{ radio_error: isActive && answer.id == checkedErrorAnswerIdObj[item.id] }"
                                                :disabled="tempQuestionObj[item.id] !== '' && tempQuestionObj[item.id] !== answer.id"
                                                :label="String.fromCharCode(65 + ind) + '. ' + answer.content"
                                                :value="answer.id" />
                                        </div>
                                    </el-radio-group>
                                </template>
                                <!-- 多选框 -->
                                <template v-if="item.type == 2">
                                </template>

                                <div v-show="answerShow" class="answerdiv">

                                    答案分析：{{ answerResultTxt }}

                                </div>

                            </el-card>

                        </el-carousel-item>
                    </template>

                </el-carousel>
                <div class="btn-center-div" v-show="btnShowFlag">
                    <el-button type="primary" @click="prev" :icon="Back">上一页</el-button>
                    <el-button :type="starBtnType" @click="starQuestion" :icon="Star" circle />

                    <el-popover ref="popoverRef" placement="top" title="答题卡" popper-style="height:210px;" :width="380"
                        trigger="click" content="状态说明：">
                        <template #reference>
                            <el-button type="info" :icon="Grid" circle />
                        </template>
                        <template #default>
                            <div class="status-desc-div">
                                状态说明: <el-button size="small" type="success" circle />对<el-button size="small"
                                    type="danger" circle />错<el-button size="small" circle />未做
                            </div>
                            <el-scrollbar height="140px" :always="true">
                                <div class="pop-question-btn" v-for="(item, index) in questionAndAnswerData"
                                    :key="index">
                                    <template v-if="item.answerResult === 'false'">
                                        <el-button type="danger" @click="handleClickQuestionId(item.id)" circle>{{ index
                                            + 1 }}</el-button>
                                    </template>
                                    <template v-else-if="item.answerResult === 'true'">
                                        <el-button type="success" @click="handleClickQuestionId(item.id)" circle>{{
                                            index + 1 }}</el-button>
                                    </template>
                                    <template v-else>
                                        <el-button @click="handleClickQuestionId(item.id)" circle>{{ index + 1
                                            }}</el-button>
                                    </template>
                                </div>
                            </el-scrollbar>
                        </template>
                    </el-popover>
                    <el-button type="success" @click="next" :icon="Right">下一页</el-button>
                </div>
            </el-card>

        </el-col>
    </el-row>
</template>

<script setup name="answer">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ArrowDown, Search, Plus, Edit, Delete, Switch, Back, Right, Star, Grid } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { QuestionCategory, QuestionBank, Question } from '/@/api'

const tpn = ref(true)
const teamPerNum = (team) => {

    if (tpn.value) {
        return team.questionIndex == 0 ? 0 : Math.round(team.questionIndex / team.questionNum * 100)
    }

}

//折叠面板的model，默认不展开
const activeNames = ref([])
/**
 * dropdown的command方法回调函数，传入的是 el-dropdown-item :command="item.id"的值
 */
const handleCommand = (bankId) => {
    initCategoryList(bankId)
}

const bankList = ref([])
const bank = reactive({
    id: '',
    name: ''
})

/**
 * 初始化题库列表集合，放入bankList集合中，并且将第一个题库的name和id赋值给bank，进行页面显示，并调用initCategoryList
 */
const initQuestionBankList = async () => {
    await QuestionBank.getAllBankList().then((res) => {
        let data = res.data
        bankList.value = data
        bank.id = data[0] == null ? '' : data[0].id
        bank.name = data[0] == null ? '' : data[0].name
        initCategoryList(bank.id)
    })
}

//知识点类型->题组的数据集合 id、label、childrend:[{题组}]
const teamNumData = ref([])

/**
 * 根据题库id查询知识点下面的题组
 */
const initCategoryList = async (id) => {

    await QuestionCategory.getCategoryAndTeamListAndQuestionNum(id).then((res) => {
        let data = res.data
        teamNumData.value = data;
    })
}
onMounted(() => {
    initQuestionBankList()

})

//答题相关事件
//为赋值选错选项按钮的错误样式
const isActive = ref(false)
//答案分析显示的文字描述
const answerResultTxt = ref('')
//是否显示答案分析
const answerShow = ref(false)
//设置选择的错题的id
const checkedErrorAnswerIdObj = reactive({})

/**
 * 判断选中的单选框是否是正确答案，并调用后台提交答案方法
 * @param questionId 问题id
 * @param rightAnswerId 正确答案的id
 * @param selectId 按钮选择的答案id
 */
const radioAnswer = (questionId, rightAnswerId, selectId) => {

    //判断是否是正确答案，不是正确答案，把选中效果设置为正确答案，并且把选中的错误答案设置背景色红色
    //此分页的单选组的v-model的对象
    if (tempQuestionObj[questionId] != rightAnswerId) {

        //把选中的按钮的value的id赋值给isCheckId，选中的id
        checkedErrorAnswerIdObj[questionId] = selectId
        //设置按钮选中正确答案
        tempQuestionObj[questionId] = rightAnswerId

        //错误的答案描述
        let errorStr = "";
        //正确的答案描述
        let rightStr = "";
        const answerList = questionAnswerListObj[questionId]

        for (let i = 0; i < answerList.length; i++) {
            const answer = answerList[i];
            if (answer.id == selectId) {
                errorStr = String.fromCharCode(65 + i)
            }
            if (answer.id == rightAnswerId) {
                rightStr = String.fromCharCode(65 + i)
            }
        }

        //设置选中的颜色变为红色，
        //document.querySelector(`.el-radio-button input[value=${selectId}]`).parentElement.classList.add('radio_error');
        isActive.value = true

        answerResultTxt.value = `您选择的答案是：${errorStr},正确答案为：${rightStr}`;
        answerShow.value = true
        //做错了题目，给对象赋值
        questionAndAnswerData.value[currentIndex.value - 1].answerResult = 'false'

    } else {
        //做题正确了，666
        questionAndAnswerData.value[currentIndex.value - 1].answerResult = 'true'

    }

    Question.submitAnswers(questionId, selectId)
}

/**
 * 清空初始化对题目选择答案需要用的对象
 */
const clearAnswerShowData = () => {
    answerResultTxt.value = '';
    answerShow.value = false
    isActive.value = false
    starBtnType.value = 'info'
}

//题目列表和题目对应的答案选项列表
const questionAndAnswerData = ref([])
//动态设置model为该面板的问题id
const tempQuestionObj = reactive({})
//设置为对象key为题目id，value为答案集合
const questionAnswerListObj = reactive({})

//设置当前跑马灯页面的题目id
const nowDoingQuestiongIdByTeam = ref('')
//设置是顺序答题还是乱序答题
// true-为顺序，false-乱序
const sortFlag = ref(true)

/**
 * 根据题组id查询问题
 * @param teamId 
 */
const getQuestion = async (teamId) => {

    //继续做题，arousel跳转到对应的页面
    await Question.getQuestionsByTeam(teamId, sortFlag.value).then((res) => {
        questionAndAnswerData.value = res.data;

        questionAndAnswerData.value.forEach((q) => {

            if (q.answerResult == null || q.answerResult == "") {
                tempQuestionObj[q.id] = ''
                checkedErrorAnswerIdObj[q.id] = ''
            } else {
                tempQuestionObj[q.id] = q.rightAnswerId
                checkedErrorAnswerIdObj[q.id] = q.checkedAnserId
            }


            questionAnswerListObj[q.id] = q.answerList
        })
    })
}


const currentTeamId = ref('')

const btnShowFlag = ref(false)
/**
 * 点击左侧题组内容右侧显示题目信息方法
 * @param teamId 题组id
 * @param questionIndex 当前题目序号
 * @param questionId 当前题目的id
 */
const handlerQuestionDetail = (teamId, questionIndex, questionId) => {

    if (teamId == currentTeamId.value) {

        ElMessage({
            message: '当前选中的就是此题组，请继续答题',
            type: 'warning',
        })
        return
    }

    if (questionIndex != 0) {
        ElMessageBox.confirm(
            `上次做到第${questionIndex}题，是否继续?`,
            'info',
            {
                distinguishCancelAndClose: true,
                confirmButtonText: '继续',
                cancelButtonText: '重新答题',
                type: 'info',
                center: true,
            }
        )
            .then(async () => {
                clearAnswerShowData()
                nowDoingQuestiongIdByTeam.value = 0
                questionAndAnswerData.value = []
                //继续做题，arousel跳转到对应的页面
                getQuestion(teamId)
                nowDoingQuestiongIdByTeam.value = questionId
                currentTeamId.value = teamId

                btnShowFlag.value = true
            })
            .catch((action) => {

                if (action === 'cancel') {

                    //重新开始答题，先清除redis中的答题信息
                    clearRedisData(teamId)

                    clearAnswerShowData()
                    nowDoingQuestiongIdByTeam.value = 0
                    questionAndAnswerData.value = []
                    //重新开始按钮，carousel跳转到第一页并且调用后台清空改teamId下面的做题的正确/错误的redis
                    getQuestion(teamId)

                    nowDoingQuestiongIdByTeam.value = 1
                    currentTeamId.value = teamId
                    btnShowFlag.value = true
                }
                //close关闭类型不做任何操作
            })
    } else {
        getQuestion(teamId)
        nowDoingQuestiongIdByTeam.value = 1
        currentTeamId.value = teamId
        btnShowFlag.value = true
    }
}

const clearRedisData = async (teamId) => {
    await Question.clearRedistData(teamId)
}

const carousel = ref()

/**
 * 监听问题列表的数据改变，进行更新nowDoingQuestiongIdByTeam当前问题的id,对carousel的页数进行跳转
 */
watch(questionAndAnswerData, () => {
    console.log(nowDoingQuestiongIdByTeam.value)
    nextTick(() => {
        if (questionAndAnswerData.value.length > 0) {
            carousel.value.setActiveItem(nowDoingQuestiongIdByTeam.value)
        }

    })
})



const prev = () => {
    if (currentIndex.value == 1) {
        return ElMessage.info("已经是第一题")
    }
    carousel.value.prev();
    clearAnswerShowData()
}
const next = () => {
    carousel.value.next();
    clearAnswerShowData()
}
//判断是否收藏该题目
const starBtnType = ref('info')

//获取做题进度条
const progressNum = ref(0)
/**
 * 监听的change,点击star按钮使用问题id进行收藏操作,当前走马灯页面的问题id
 */
const currentCarouselQuestionId = ref('')
//当前的页数并不是下标，所以
const currentIndex = ref('')
/**
 * carousel的改变方法 currentId 翻页到新页面的索引
 */
const handleChange = (currentId, prevId) => {

    console.log("currentId:" + currentId)
    if (currentId === 0) {
        return
    }

    currentIndex.value = currentId

    let currentNum = currentId;
    let num = currentNum == 0 ? 0 : (currentNum / questionAndAnswerData.value.length).toFixed(2) * 100
    progressNum.value = num

    //通过carousel的索引id,设置当前的走马灯页面的问题id，用于点击star收藏使用
    currentCarouselQuestionId.value = questionAndAnswerData.value[currentId - 1].id;


    if (checkedErrorAnswerIdObj[currentCarouselQuestionId.value] !== ""
        && checkedErrorAnswerIdObj[currentCarouselQuestionId.value] !== tempQuestionObj[currentCarouselQuestionId.value]) {
        console.log(checkedErrorAnswerIdObj[currentCarouselQuestionId.value], tempQuestionObj[currentCarouselQuestionId.value]);

        isActive.value = true
    }


    //是否为
    let isStar = questionAndAnswerData.value[currentId - 1].isStar;
    if (isStar == '1') {
        starBtnType.value = 'warning'
    } else {
        starBtnType.value = 'info'
    }
}

const starQuestion = async () => {



    //已经是收藏的，进行取消收藏，
    let qId = currentCarouselQuestionId.value
    console.log(currentIndex.value)
    //因为currentIndex是下标，默认设置了0页，所以currentIndex从1页开始，所以根据索引下标获取数据时需要-1
    if (questionAndAnswerData.value[currentIndex.value - 1].isStar == '1') {
        await Question.postStarQuestion(qId, '0').then(res => {
            questionAndAnswerData.value[currentIndex.value - 1].isStar = '0'
            starBtnType.value = 'info'
        })
        //post /qId/0
    } else {
        //进行收藏
        //post /1
        await Question.postStarQuestion(qId, '1').then(res => {
            questionAndAnswerData.value[currentIndex.value - 1].isStar = '1'
            starBtnType.value = 'warning'

        })
    }

}

const popoverRef = ref()
const handleClickQuestionId = (questionId) => {
    carousel.value.setActiveItem(questionId)
    popoverRef.value.hide()

}

</script>

<style lang="scss" scoped>
.collect-shuffle-font {
    display: inline-block;
    padding-left: 20px;
    padding-top: 10px;
}

.status-desc-div {
    font-size: 12px;
}

.btn-center-div {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 10px;

}

.pop-question-btn {
    display: inline-block;
    padding: 3px;
}

.radio_error {
    background-color: #f56c6c !important;

}

.radio_error :deep(.el-radio-button__inner) {
    background-color: #f56c6c !important;
    border-color: #f56c6c !important;
}

.right-card {
    width: 100%;
    height: 100%;
}

.maxh100 {
    max-height: 100%;
    width: 100%;
    overflow: hidden;
}

.el-row {
    margin-left: 20px;
}

.question-content {
    font-size: 2rem;
}

.answer-item {
    display: flex;
    align-items: center;
    justify-items: center;
    margin-top: 15px;
    margin-left: 10px;
}

.radio-column {
    display: flex;
    flex-direction: column;
    align-items: initial;
}

:deep(.el-collapse-item__header) {
    padding-left: 8px;
}

.dropdown-font {
    margin-top: 10px;
    margin-bottom: 10px;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    display: flex;
    align-items: center;
    font-size: 1.5rem;
}

.team-progress {
    width: 100%;
    max-width: 200px;

}

.perItem {
    width: 100%;
}

.team-card {
    margin-bottom: 5px;
}

.team-card :deep(.el-card__header) {
    padding-bottom: 0px;
    padding-top: 0px;
    height: 35px;
    display: flex;
    justify-items: center;
    align-items: center;
}

:deep(.el-carousel__container) {
    height: 550px;
    position: relative;
}

:deep(.el-radio-button__original-radio:disabled+.el-radio-button__inner) {
    cursor: pointer;
}

:deep(.el-radio-button__inner) {
    font-size: 1.5rem;
}

.answerdiv {
    width: 100%;
    height: 100%;
    margin-bottom: 0px;
    margin-top: 40px;
    font-size: 1.5rem;
}
</style>